<?php
class News_Model_News extends Promotor_Model_Abstract {

	protected $_dbTableClass = 'News_Model_DbTable_News';

	protected $_cachedMethods = array(
		'findById',
		'findByAlias',
		'getAttachedSitesId',
		'fetchAllPublicatedOrderByTimeCreate'
	);
	
	/**
	 * @return Zend_Db_Table_Select
	 */
	public function selectList() {
		$table = $this->getDbTable();
		$adapter = $table->getAdapter();

		/* @var $select Zend_Db_Select */
		$select = new Zend_Db_Select($adapter);
		$select
			->from(array('shn' => 'site_has_news'))
			->joinInner(array('n' => 'news'), 'n.id = shn.news_id' , '*')
			->joinLeft(array('s' => 'site'), 's.id = shn.site_id', array('site_name' => 'name'));

		return $select;
	}
	
	/**
	 * @param integer $id
	 * @return array
	 */
	public function findById($id, $asArray = true) {
		$table = $this->getDbTable();
		try {
			$rowset = $table->find((int) $id);
			if(!count($rowset)) {
				$this->_setStatus(self::FAILURE);
				return;
			}

			$this->_setStatus(self::SUCCESS);

			$current = $rowset->current();
			return $asArray
				? $current->toArray()
				: $current;
		} catch (Zend_Db_Table_Exception $e) {
			$this->_setStatus(self::FAILURE);
			$this->_addMessage($e->getMessage());
		}
	}
	
	/**
	 * @param string $alias
	 * @return array
	 */
	public function findByAlias($alias) {
		$table = $this->getDbTable();
		$where = $table->getAdapter()->quoteInto('alias = ?', $alias);

		try {
			$row = $table->fetchRow($where);
			if(!$row instanceof Zend_Db_Table_Row_Abstract) {
				$this->_setStatus(self::FAILURE);
				return;
			}
			$this->_setStatus(self::SUCCESS);
			return $row->toArray();
		} catch (Zend_Db_Table_Exception $e) {
			$this->_setStatus(self::FAILURE);
			$this->_addException($e);
		}
	}
	
	/**
	 * @param integer $newsId
	 * @return array
	 */
	public function getAttachedSitesId($newsId) {
		$table = $this->getDbTable();
		$select = $table->select()->where('id = ?', $newsId);
		try {
			$row = $table->fetchRow($select);
		} catch (Zend_Db_Exception $e) {
			$this->_addException($e);
			$this->_setStatus(self::FAILURE);
			return;
		}
		
		if (!$row instanceof Zend_Db_Table_Row_Abstract) {
			$this->_setStatus(self::FAILURE);
			return;
		}

		try {
			$rowset = $row->findDependentRowset('Site_Model_DbTable_HasNews','News');
		} catch (Zend_Db_Exception $e) {
			$this->_addException($e);
			$this->_setStatus(self::FAILURE);
			return;
		}
		
		$return = array();
		foreach ($rowset as $row) {
			$return[] = $row->site_id;
		}
		
		$this->_setStatus(self::SUCCESS);
		return $return;
	}
	
	/**
	 * @param image $page
	 * @param image $itemCountPerPage
	 * @return array as array(array $data, Zend_Db_Select $select);
	 */
	public function fetchAllPublicatedOrderByTimeCreate($page = null, $itemCountPerPage = null) {
		$table = $this->getDbTable();

		/* @var $select Zend_Db_Select */
		$select = $table->select()
			->where('publicated')
			->order('time_create');

		if (is_numeric($page) && is_numeric($itemCountPerPage)) {
			$select->limitPage($page, $itemCountPerPage);
		}

		try {
			$rowset = $table->fetchAll($select);
			$data = $rowset->toArray();

			$this->_setStatus(self::SUCCESS);
			return array($data, $select);
		} catch (Zend_Db_Exception $e) {
			$this->_addException($e);
			$this->_setStatus(self::FAILURE);			
		}
	}

	/**
	 * @param array $data
	 * @return void
	 */
	public function editableUpdate(array $data) {
		$table = $this->getDbTable();
		$db = $table->getAdapter();

		$parentKey = $table->info(Zend_Db_Table::PRIMARY);
		$whereBase = implode(' = %s AND ', $parentKey) . ' = %s';
		
		$db->beginTransaction();
		try {
			foreach ($data as $key => $values) {
				$key = explode(KontorX_DataGrid_Cell_Editable_Abstract::SEPARATOR, $key);
				$where = vsprintf($whereBase, $key);
				$table->update($values, $where);
			}
			$db->commit();
			
			// notify observers
			$manager = Promotor_Observable_Manager::getInstance();
			$list = $manager->notify('news_edit_post');
			$this->_addMessages($list->getMessages());
			
			$this->_setStatus(self::SUCCESS);
		} catch (Zend_Db_Table_Exception $e) {
			$db->rollBack();
			$this->_setStatus(self::FAILURE);
			$this->_addMessage($e->getMessage());
		}
	}
	
	/**
	 * @param array $data
	 * @return void
	 */
	public function editableDelete(array $data) {
		$table = $this->getDbTable();
		$db = $table->getAdapter();

		$parentKey = $table->info(Zend_Db_Table::PRIMARY);
		$whereBase = implode(' = %s AND ', $parentKey) . ' = %s';
		
		$db->beginTransaction();
		try {
			foreach ($data as $key => $values) {
				// większe od zera .. zakładam że autoincrement jest od 1..
				if (isset($values['id']) && $values['id'] > 0) {
					// TODO Nalezy pamiętać o tym że mogą to być rekordy z tree..
					$key = explode(KontorX_DataGrid_Cell_Editable_Abstract::SEPARATOR, $key);
					$where = vsprintf($whereBase, $key);
					$table->delete($where);
				}
			}
			
			$db->commit();
			$this->_setStatus(self::SUCCESS);
		} catch (Zend_Db_Table_Exception $e) {
			$db->rollBack();
			$this->_setStatus(self::FAILURE);
			$this->_addMessage($e->getMessage());
		}
	}
}